/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import 'vs/css!vs/workbench/contrib/wechat/browser/media/wechat';

import { CancellationToken } from 'vs/base/common/cancellation';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { localize } from 'vs/nls';
import { IEditorOpenContext } from 'vs/workbench/common/editor';
import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { Dimension } from 'vs/base/browser/dom';
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';

// 导入WechatEditorInput
import { WechatEditorInput, WechatUser } from 'vs/workbench/contrib/wechat/browser/wechatEditorInput';

// 聊天消息接口
interface ChatMessage {
	sender: string;
	content: string;
	isMe: boolean;
	timestamp: Date;
}

export class WechatEditor extends EditorPane {
	static readonly ID = 'wechatEditor';

	private _container: HTMLElement | undefined;
	private readonly _disposables = new DisposableStore();
	private _selectedUser: WechatUser | undefined;
	private _chatMessages = new Map<string, ChatMessage[]>();

	// 储存最后选择的用户，供可见性变化时使用
	static _lastSelectedUser: WechatUser | undefined;

	constructor(
		group: IEditorGroup,
		@ITelemetryService telemetryService: ITelemetryService,
		@IThemeService themeService: IThemeService,
		@IStorageService storageService: IStorageService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super(WechatEditor.ID, group, telemetryService, themeService, storageService);
		console.log('[WechatEditor] Created new wechat editor');
	}

	/**
	 * 创建编辑器
	 */
	protected createEditor(parent: HTMLElement): void {
		this._container = parent;
		this._container.classList.add('wechat-editor');
		console.log('[WechatEditor] Creating editor container');
		this.createEditorContent();
	}

	/**
	 * 处理编辑器可见性变化
	 */
	protected override setEditorVisible(visible: boolean): void {
		super.setEditorVisible(visible);

		console.log('[WechatEditor] 编辑器可见性变化:', visible);

		// 当编辑器变为可见时，使用最后保存的用户
		if (visible) {
			if (WechatEditor._lastSelectedUser) {
				console.log('[WechatEditor] 编辑器激活，使用之前保存的用户:', WechatEditor._lastSelectedUser.name);
				this._selectedUser = { ...WechatEditor._lastSelectedUser };
				this.createEditorContent();
			} else if (this.input instanceof WechatEditorInput && this.input.selectedUser) {
				console.log('[WechatEditor] 编辑器激活，使用输入中的用户:', this.input.selectedUser.name);
				this._selectedUser = { ...this.input.selectedUser };
				// 保存此用户
				WechatEditor._lastSelectedUser = { ...this.input.selectedUser };
				this.createEditorContent();
			}
		}
	}

	private createEditorContent(): void {
		if (!this._container) {
			console.error('[WechatEditor] Container not found');
			return;
		}

		console.log('[WechatEditor] Creating editor content, selectedUser:', this._selectedUser?.name);

		// 清除容器内容
		while (this._container.firstChild) {
			this._container.removeChild(this._container.firstChild);
		}

		// 创建编辑器界面
		const contentContainer = document.createElement('div');
		contentContainer.className = 'wechat-editor-content';

		// 创建消息列表
		const messageList = document.createElement('div');
		messageList.className = 'wechat-message-list';

		// 如果有选中的用户，显示该用户的聊天记录
		if (this._selectedUser) {
			const userName = this._selectedUser.name;
			console.log('[WechatEditor] Rendering messages for user:', userName);

			// 获取用户聊天记录
			const messages = this.getChatMessages(userName);
			console.log('[WechatEditor] Found messages:', messages.length);

			// 显示聊天记录
			messages.forEach(message => {
				if (message.isMe) {
					messageList.appendChild(this.createSentMessage(message.content));
				} else {
					messageList.appendChild(this.createReceivedMessage(message.sender, message.content));
				}
			});
		} else {
			console.log('[WechatEditor] No user selected, showing welcome message');
			// 如果没有选中用户，显示欢迎消息
			const welcomeMessage = document.createElement('div');
			welcomeMessage.className = 'wechat-welcome-message';
			welcomeMessage.textContent = '请在左侧选择联系人开始聊天';
			messageList.appendChild(welcomeMessage);
		}

		// 创建输入区域
		const inputArea = document.createElement('div');
		inputArea.className = 'wechat-input-area';

		const textInput = document.createElement('textarea');
		textInput.className = 'wechat-input';
		textInput.placeholder = localize('wechat.input.placeholder', 'Type a message...');

		const sendButton = document.createElement('button');
		sendButton.className = 'wechat-send-button';
		sendButton.textContent = localize('wechat.send', 'Send');

		// 发送消息事件
		const sendMessage = () => {
			const message = textInput.value.trim();
			if (message && this._selectedUser) {
				// 添加消息到UI
				messageList.appendChild(this.createSentMessage(message));
				textInput.value = '';
				// 自动滚动到底部
				messageList.scrollTop = messageList.scrollHeight;

				// 添加到聊天记录
				this.addMessage(this._selectedUser.name, 'You', message, true);

				// 模拟回复
				setTimeout(() => {
					const replyContent = `我是${this._selectedUser!.name}，我收到了你的消息：${message}`;
					messageList.appendChild(this.createReceivedMessage(this._selectedUser!.name, replyContent));
					// 自动滚动到底部
					messageList.scrollTop = messageList.scrollHeight;

					// 添加到聊天记录
					this.addMessage(this._selectedUser!.name, this._selectedUser!.name, replyContent, false);
				}, 1000);
			}
		};

		// 添加发送按钮点击事件
		sendButton.addEventListener('click', sendMessage);

		// 添加回车发送功能
		textInput.addEventListener('keydown', (e) => {
			if (e.key === 'Enter' && !e.shiftKey) {
				e.preventDefault();
				sendMessage();
			}
		});

		inputArea.appendChild(textInput);
		inputArea.appendChild(sendButton);

		// 添加到主容器
		contentContainer.appendChild(messageList);
		contentContainer.appendChild(inputArea);
		this._container.appendChild(contentContainer);
	}

	/**
	 * 获取用户的聊天记录
	 */
	private getChatMessages(userName: string): ChatMessage[] {
		if (!this._chatMessages.has(userName)) {
			// 创建模拟聊天记录
			const messages: ChatMessage[] = [];

			switch (userName) {
				case '阿莲':
					messages.push(this.createMessage('阿莲', 'Hello，有什么可以帮你的吗？', false));
					messages.push(this.createMessage('You', '我想了解一下VSCode的扩展开发', true));
					messages.push(this.createMessage('阿莲', 'VSCode扩展开发是使用TypeScript/JavaScript创建自定义功能的过程。你可以添加自定义命令、视图、编辑器功能等。要开始，你需要安装yo和generator-code，然后用它生成项目脚手架。', false));
					break;
				case '张三':
					messages.push(this.createMessage('张三', '你好，我是张三', false));
					messages.push(this.createMessage('You', '张三好，今天项目进度如何？', true));
					messages.push(this.createMessage('张三', '我们已经完成了前端界面设计，正在进行后端API对接。', false));
					break;
				case '李四':
					messages.push(this.createMessage('李四', '明天开会记得带上项目文档', false));
					messages.push(this.createMessage('You', '好的，我已经准备好了', true));
					messages.push(this.createMessage('李四', '还需要演示一下新功能的使用方法', false));
					break;
				case '王五':
					messages.push(this.createMessage('王五', '周末有时间讨论一下新项目吗？', false));
					messages.push(this.createMessage('You', '可以，下午2点如何？', true));
					messages.push(this.createMessage('王五', '没问题，到时见', false));
					break;
				default:
					messages.push(this.createMessage(userName, `你好，我是${userName}`, false));
					messages.push(this.createMessage('You', `你好，${userName}`, true));
			}

			this._chatMessages.set(userName, messages);
		}

		return this._chatMessages.get(userName) || [];
	}

	/**
	 * 创建一条聊天消息
	 */
	private createMessage(sender: string, content: string, isMe: boolean): ChatMessage {
		return {
			sender,
			content,
			isMe,
			timestamp: new Date()
		};
	}

	/**
	 * 添加一条消息到用户的聊天记录
	 */
	private addMessage(userName: string, sender: string, content: string, isMe: boolean): void {
		const messages = this.getChatMessages(userName);
		messages.push(this.createMessage(sender, content, isMe));
	}

	/**
	 * 创建接收到的消息元素
	 */
	private createReceivedMessage(username: string, content: string): HTMLElement {
		const message = document.createElement('div');
		message.className = 'wechat-message wechat-message-received';

		const header = document.createElement('div');
		header.className = 'wechat-message-header';

		const avatar = document.createElement('div');
		avatar.className = 'wechat-message-avatar';
		avatar.textContent = username.charAt(0).toUpperCase();

		const name = document.createElement('div');
		name.className = 'wechat-message-username';
		name.textContent = username;

		const time = document.createElement('div');
		time.className = 'wechat-message-time';
		time.textContent = new Date().toLocaleTimeString();

		header.appendChild(avatar);
		header.appendChild(name);
		header.appendChild(time);

		const messageContent = document.createElement('div');
		messageContent.className = 'wechat-message-content';
		messageContent.textContent = content;

		message.appendChild(header);
		message.appendChild(messageContent);

		return message;
	}

	/**
	 * 创建发送的消息元素
	 */
	private createSentMessage(content: string): HTMLElement {
		const message = document.createElement('div');
		message.className = 'wechat-message wechat-message-sent';

		const header = document.createElement('div');
		header.className = 'wechat-message-header';

		const name = document.createElement('div');
		name.className = 'wechat-message-username';
		name.textContent = 'You';

		const time = document.createElement('div');
		time.className = 'wechat-message-time';
		time.textContent = new Date().toLocaleTimeString();

		header.appendChild(name);
		header.appendChild(time);

		const messageContent = document.createElement('div');
		messageContent.className = 'wechat-message-content';
		messageContent.textContent = content;

		message.appendChild(header);
		message.appendChild(messageContent);

		return message;
	}

	/**
	 * 当编辑器输入发生变化时调用
	 */
	override async setInput(input: EditorInput, options: any, context: IEditorOpenContext, token: CancellationToken): Promise<void> {
		await super.setInput(input, options, context, token);

		// 清除之前的事件监听和状态
		this._disposables.clear();

		console.log('[WechatEditor] setInput被调用, 清除监听');

		if (input instanceof WechatEditorInput) {
			// 监听用户变化事件
			this._disposables.add(input.onDidChangeContents(() => {
				console.log('[WechatEditor] 检测到用户变更事件');

				// 使用最后保存的用户
				if (WechatEditor._lastSelectedUser) {
					console.log('[WechatEditor] 使用最后保存的用户:', WechatEditor._lastSelectedUser.name);
					this._selectedUser = { ...WechatEditor._lastSelectedUser };
					// 强制更新UI
					this.createEditorContent();
				}
			}));

			// 总是使用静态保存的最后选择的用户，忽略input中的用户
			if (WechatEditor._lastSelectedUser) {
				console.log('[WechatEditor] setInput使用静态保存的用户:', WechatEditor._lastSelectedUser.name);
				this._selectedUser = { ...WechatEditor._lastSelectedUser };

				// 修正input中的用户，避免其他地方使用错误的用户
				if (input.selectedUser?.name !== WechatEditor._lastSelectedUser.name) {
					console.log('[WechatEditor] 修正input中的用户为:', WechatEditor._lastSelectedUser.name);
					input.setSelectedUser(WechatEditor._lastSelectedUser);
				}

				// 重新创建编辑器内容
				this.createEditorContent();
			}
			// 如果没有静态用户，则使用input中的用户（仅作为后备选项）
			else if (input.selectedUser) {
				console.log('[WechatEditor] 无静态用户，使用input中的用户:', input.selectedUser.name);
				this._selectedUser = { ...input.selectedUser };
				// 设置为静态用户
				WechatEditor._lastSelectedUser = { ...input.selectedUser };
				// 重新创建编辑器内容
				this.createEditorContent();
			}
			// 如果都没有用户
			else {
				console.log('[WechatEditor] 无用户可设置');
				this._selectedUser = undefined;
				// 重新创建编辑器内容
				this.createEditorContent();
			}
		}
	}

	/**
	 * 调整编辑器大小
	 */
	layout(dimension: Dimension): void {
		if (this._container) {
			this._container.style.width = `${dimension.width}px`;
			this._container.style.height = `${dimension.height}px`;
		}
	}

	override dispose(): void {
		console.log('[WechatEditor] Disposing');
		this._disposables.dispose();
		super.dispose();
	}

	// 设置最后选择的用户
	static setLastSelectedUser(user: WechatUser): void {
		console.log('[WechatEditor] 静态方法设置最后选择的用户:', user.name);
		WechatEditor._lastSelectedUser = { ...user };
	}
}
